import React, {useEffect} from 'react';
import {SafeAreaView, ToastAndroid, View} from "react-native";
import { StyleSheet } from 'react-native';
import {
    Button,
    Card, IndexPath, Layout, Popover, Select, SelectItem,
    Text,
} from '@ui-kitten/components';
import {ServicingTicketScreen} from "./ServicingTicketScreen";
import FatchManager from "../Compoments/FatchManager";
import SorageManager from "../Compoments/SorageManager";
import {assertSourceType} from "@babel/core/lib/config/validation/option-assertions";




export const AddTicketCollectionScreen = ({ route,navigation }) => {
    const [trainInf, setTrainInf] = React.useState([]);
    const [firstData, setFirstData] = React.useState('');
    const [secondData, setSecodeData] = React.useState([]);
    const [thirdData, setThirdData] = React.useState([]);
    const [forthData, setForthData] = React.useState([]);
    const [fivethData, setFiveData] = React.useState([]);


    const [selectedFirstIndex, setSelectedFirstIndex] = React.useState(new IndexPath(0));
    const [selectedSecondIndex, setSelectedSecondIndex] = React.useState(new IndexPath(0));
    const [selectedThirdIndex, setSelectedThirdIndex] = React.useState(new IndexPath(0));
    const [selectedFourthIndex, setSelectedFourthIndex] = React.useState(new IndexPath(0));
    const [selectedFivethIndex, setSelectedFivethIndex] = React.useState(new IndexPath(0));



    const [displayFirstValue, setDisplayFirstValue] = React.useState("请选择");
    const [displaySecondValue, setDisplaySecondValue] = React.useState("请选择");
    const [displayThirdValue, setDisplayThirdValue] = React.useState("请选择");
    const [displayFourthValue, setDisplayFourthValue] = React.useState("请选择");
    const [displayFivethValue, setDisplayFivethValue] = React.useState("请选择");
    // const displayFirstValue = trainInf[setSelectedFirstIndex];


    const [hid, setHid] = React.useState("");
    const [setResult,setSetResult] = React.useState("");






    const {ch,cx,cxid,id} = route.params;


    const Header = (props) => (
        <View {...props}>
            <Text category='h6'>机车：
                {ch}/{cx}
            </Text>
        </View>
    );



    //------------------页面跳转---------------------//
    const navigateServicingTicket = () => {
        navigation.navigate('ServicingTicket');
    };

    //-----------------fetch api-----------------------------//


    /**
     * 获取第一级故障内容
     */
    const  getTrainFirstPart=()=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

          fetch("http://htjoa.nrnet.cn/dc14/jwmis/trainSecondController/second?firstid="+cxid, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取第一部分故障");
                setTrainInf(result)
               // result.map((item,index)=>{
               //     console.log(index,item)
               // })
            })
            .catch(error => {
                console.log('error', error)
                console.log("出现问题")
            });


    }

    /**
     *获取第二级故障内容
     */
    const  getTrainSecondPart=(secondid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        console.log("getTrainSecondPart")
        fetch("http://htjoa.nrnet.cn/dc14/jwmis/trainThirdController/third?secondid="+secondid, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取第二部分故障");
                    setSecodeData(result)
            })
            .catch(error => {
                console.log('error', error)
                console.log("请检查网络")
            });


    }


    /**
     *获取第三级故障内容
     */
    const  getTrainThirdPart=(thirdid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        console.log("getTrainSecondPart")
        fetch("http://htjoa.nrnet.cn/dc14/jwmis/trainFourthPartController/fourth?thirdid="+thirdid, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取第三部分故障");
                setThirdData(result)
            })
            .catch(error => {
                console.log('error', error)
                console.log("请检查网络")
            });


    }


    /**
     *获取第四级故障内容
     */
    const  getTrainFourthPart=(fourthid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        console.log("getTrainSecondPart")
        fetch("http://htjoa.nrnet.cn/dc14/jwmis/trainFivePartController/fiveth?fourthid="+fourthid, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取第四部分故障");
                setForthData(result)
            })
            .catch(error => {
                console.log('error', error)
                console.log("请检查网络")
            });


    }


    /**
     *获取第五级故障内容
     */
    const  getTrainFivethPart=(fivethpartid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        console.log("getTrainSecondPart")
        fetch("http://htjoa.nrnet.cn/dc14/jwmis/trainSixPartController/sixth?fivethpartid="+fivethpartid, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取第五部分故障");
                setFiveData(result)
            })
            .catch(error => {
                console.log('error', error)
                console.log("请检查网络")
            });


    }


    /**
     * 添加按钮逻辑
     */
    const setTrainInfWork=()=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        SorageManager.get('userInf').then(r =>{
            SorageManager.get("search").then(s=>{
                // getPreparInfList(r["belongduan"],null)
                const url = "http://htjoa.nrnet.cn/dc14/jwmis/zbclcrk/set?id="+id+"&hid="+hid+"&hxtqr="+r["userid"];
                console.log(url)
                fetch(url, requestOptions)
                    .then(response => response.text())
                    .then(result => {

                        if (result==='isAdded'){
                            showToast("请勿重复提活")
                        }if(result==="false"){
                            showToast("提活遇到问题，请刷新页面")
                        }else {
                            setSetResult(result);
                        }


                    })
                    .catch(error => {
                        console.log('error', error)
                        console.log("请检查网络")
                    });

            })

        } )
    }

    /**
     * 安卓Toast组件
     * @param message
     */
    const showToast = (message) => {
        ToastAndroid.show(message, ToastAndroid.SHORT);
    };


    useEffect(()=>{
        getTrainFirstPart()

        console.log(trainInf)

    },[])




    const [visible, setVisible] = React.useState(false);

    const renderToggleButton = () => (
        <Button
            style={styles.footerControl}
            onPress={() => setVisible(true)}>
          添加
        </Button>
    );





    const renderOption = (title) => (
        <SelectItem title={title}/>
    );


    return (
        <SafeAreaView style={{flex:1}}>
            <Card style={styles.card} header={Header} >
                <Layout >

                    {/*第一部分故障选择*/}
                    <Select
                        style={{marginBottom:40,marginTop:30}}
                        placeholder='请选择'
                        value={displayFirstValue}
                        selectedIndex={selectedFirstIndex}
                        onSelect={index => {setSelectedFirstIndex(index)
                            setDisplayFirstValue(trainInf[index["row"]]["name"])
                            getTrainSecondPart(trainInf[index["row"]]["id"])
                            setDisplaySecondValue("请选择")
                            setDisplayThirdValue("请选择")
                            setDisplayFourthValue("请选择")
                            setDisplayFivethValue("请选择")
                            setThirdData([])
                            setForthData([])
                            setFiveData([])
                        }
                    }>
                        {
                            trainInf.map((item,index)=>{
                               return(  <SelectItem key={index} title={item["name"]}/>)
                            })
                        }
                        {/*{firstData.map["name"](renderOption)}*/}
                    </Select>

                    {/*第二部分故障选择*/}
                    <Select style={{marginBottom:40}}
                            placeholder='请选择'
                            value={displaySecondValue}
                            selectedIndex={selectedSecondIndex}
                            onSelect={index => {setSelectedSecondIndex(index)
                                setDisplaySecondValue(secondData[index["row"]]["name"])
                                getTrainThirdPart(secondData[index["row"]]["id"])
                                setDisplayThirdValue("请选择")
                                setDisplayFourthValue("请选择")
                                setDisplayFivethValue("请选择")
                                setForthData([])
                                setFiveData([])

                            }}
                    >

                        {
                            secondData.map((item,index)=>{
                                return(  <SelectItem key={index} title={item["name"]}/>)
                            })
                        }

                    </Select>

                    {/*第三部分故障*/}
                    <Select
                        style={{marginBottom:40}}
                        placeholder='请选择'
                        value={displayThirdValue}
                        selectedIndex={selectedThirdIndex}
                        onSelect={index => {setSelectedThirdIndex(index)
                            setDisplayThirdValue(thirdData[index["row"]]["name"])
                            getTrainFourthPart(thirdData[index["row"]]["id"])
                            setDisplayFourthValue("请选择")
                            setDisplayFivethValue("请选择")
                            setFiveData([])

                        }}

                       >

                        {
                            thirdData.map((item,index)=>{
                                return(  <SelectItem key={index} title={item["name"]}/>)
                            })
                        }


                    </Select>

                    {/*第四部分故障*/}
                     <Select
                        style={{marginBottom:40}}

                        placeholder='请选择'
                        value={displayFourthValue}
                        selectedIndex={selectedFourthIndex}
                        onSelect={index => {setSelectedFourthIndex(index)
                            setDisplayFourthValue(forthData[index["row"]]["name"])
                            getTrainFivethPart(forthData[index["row"]]["id"])
                            setDisplayFivethValue("请选择")

                        }}

                        >
                        {
                            forthData.map((item,index)=>{
                                return(  <SelectItem key={index} title={item["name"]}/>)
                            })
                        }
                    </Select>

                    {/*第五部分故障*/}
                    <Select
                        style={{marginBottom:40}}

                        placeholder='请选择'
                        value={displayFivethValue}
                        selectedIndex={selectedFivethIndex}
                        onSelect={index => {setSelectedFivethIndex(index)
                            setDisplayFivethValue(fivethData[index["row"]]["name"])
                            setHid(fivethData[index["row"]]["id"])
                        }}
                        >
                        {
                            fivethData.map((item,index)=>{
                                return(  <SelectItem key={index} title={item["name"]}/>)
                            })
                        }
                    </Select>

                </Layout>


            </Card>


            <Button
                onPress={navigateServicingTicket}
                style={styles.footerControl}
                appearance='outline'
                status='warning'>
                结束
            </Button>

            <Button
                style={styles.footerControl}
                onPress={()=>{

                    //如果最后一项选择为空 则不能提交
                    if(displayFivethValue==="请选择"){
                        showToast("故障现象为空!")
                       console.log("故障现象为空")
                    }
                    //不为空开始做fetch 插入请求
                    else {
                        const requestOptions = {
                            method: 'GET',
                            redirect: 'follow'
                        };

                        SorageManager.get('userInf').then(r =>{
                                const url = "http://htjoa.nrnet.cn/dc14/jwmis/zbclcrk/set?id="+id+"&hid="+hid+"&hxtqr="+r["userid"];
                                console.log(url)
                                fetch(url, requestOptions)
                                    .then(response => response.text())
                                    .then(result => {
                                        console.log(result,"插入结果");
                                        if (result==="success"){
                                            const infText = displayFirstValue+displaySecondValue+displayThirdValue+displayFourthValue+displayFivethValue
                                            navigation.navigate('AddTicketSuccess',{cx:cx,ch:ch,cxid:cxid,infText:infText,id:id});
                                            // showToast("添加成功!")
                                        }
                                        if (result==='isAdded'){
                                            showToast("请勿重复提活")
                                        }if(result==="false"){
                                            showToast("提活遇到问题，请刷新页面")
                                        }
                                        // else {
                                        //     showToast("请检查网络!")
                                        // }

                                    })
                                    .catch(error => {
                                        console.log('error', error)
                                        console.log("请检查网络")
                                    });
                            }
                         )
                    }
                }}
            >
                添加
            </Button>

        </SafeAreaView>


    );
};

const styles = StyleSheet.create({
    topContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    card: {
        flex: 1,
        margin: 2,
    },
    footerContainer: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
    },
    footerControl: {
        marginHorizontal: 2,
    },
    content: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 4,
        paddingVertical: 8,
    },
    avatar: {
        marginHorizontal: 4,
    },
    backdrop: {
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },

    selecterList:{
        maxHeight:400,
        flex:1,
    }
});

